package com.CST.service.impl.cb;

import cn.hutool.crypto.SecureUtil;
import com.CST.bo.zx.ApprovalUserBO;
import com.CST.common.api.Response;
import com.CST.common.api.ResultObject;
import com.CST.dto.cb.PassWordDTO;
import com.CST.dto.cb.SysUserDTO;
import com.CST.entity.cb.*;
import com.CST.entity.zx.ZxAuth;
import com.CST.mapper.cst.cb.BdSysRoleMenuMapper;
import com.CST.mapper.cst.cb.BdSysUserMapper;
import com.CST.mapper.cst.cb.ZxCardInformationMapper;
import com.CST.service.cb.IBdSysUserService;
import com.CST.service.zx.IZxAuthService;
import com.CST.util.MD5;
import com.CST.util.UUIDUtil;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户管理 服务实现类
 * </p>
 *
 * @author y
 * @since 2021-09-27
 */
@Service
public class BdSysUserServiceImpl extends ServiceImpl<BdSysUserMapper, BdSysUser> implements IBdSysUserService {

    @Autowired
    private  BdSysUserMapper bdSysUserMapper;

    @Autowired
    private ZxCardInformationMapper zxCardInformationMapper;


    /**
     * <p>新增用户</p >
     *
     * @param bdSysUser
     * @return com.CST.common.api.Response
     *
     * @author y
     * @since 2021/09/27 09:32
     */
    @Override
    public Response insertSysUser(BdSysUser bdSysUser) {

        QueryWrapper<Object> wrapper = new QueryWrapper<>();
        wrapper.eq("USER_NAME", bdSysUser.getUserName());
        //判断用户是否已经存在
        List<BdSysUser> sysUserList = baseMapper.getUser(bdSysUser.getUserName());

        if (null != sysUserList && sysUserList.size() > 0) {
            return new Response(500, "用户已存在");
        }
        bdSysUser.setId(UUIDUtil.uuid());
        bdSysUser.setUserPassword(MD5.crypt(bdSysUser.getUserPassword()));
        bdSysUser.setCreateTime(new Date());
        bdSysUser.setDelFlag("0");
        int insert = baseMapper.insert(bdSysUser);
        if (insert > 0) {
            return new Response(200, "新增成功");
        } else {
            return new Response(500, "新增失败");
        }
    }


    /**
     * <p>修改密码</p >
     *
     * @param passWordDto
     * @return com.CST.common.api.ResultObject
     *
     * @author y
     * @since 2021/09/27 09:34
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultObject updateUserPassword(PassWordDTO passWordDto) {
        // String userId = HttpUtil.getRequestHeaderInfoByVar(Constants.USER_ID);
        String userId = passWordDto.getId();
        if (StringUtils.isEmpty(userId)) {
            return ResultObject.failed("错误");
        }
        BdSysUser bdSysUser = baseMapper.selectById(userId);
        String oldPassword = SecureUtil.md5(passWordDto.getOldUserPassword());
        if (oldPassword.equals(bdSysUser.getUserPassword())) {
            bdSysUser.setUserPassword(SecureUtil.md5(passWordDto.getNewUserPassword()));
        } else {
            return ResultObject.failed("原密码错误！");
        }
        return baseMapper.updateById(bdSysUser) > 0 ? ResultObject.success(200, "修改成功") : ResultObject.failed(
                "修改失败！");

    }

    @Override
    public ResultObject reStartPassword(String id) {

        if (StringUtils.isEmpty(id)) {
            return ResultObject.failed("错误");
        }
        BdSysUser bdSysUser = baseMapper.selectById(id);
        //https://tool.hiofd.com/md5-encrypt-online/  md5手动加密
        bdSysUser.setUserPassword(SecureUtil.md5("cbhs123456"));
        return baseMapper.updateById(bdSysUser) > 0 ? ResultObject.success(200, "初始化成功") : ResultObject.failed(
                "初始化失败！");
    }

    /**
     * <p>查询</p >
     *
     * @param realName, userName
     * @return java.util.List<com.CST.entity.cb.BdSysUser>
     *
     * @author y
     * @since 2021/10/09 10:39
     */
    @Override
    public List<BdSysUser> getUsers(String realName, String userName) {
        QueryWrapper<BdSysUser> wrapper = new QueryWrapper<>();
        wrapper.like(realName, "realName").or().like(userName, "userName");
        return baseMapper.getUsers(realName, userName);
    }

    @Override
    public List<BdSysUser> getUser(String userName) {
        return baseMapper.getUser(userName);
    }

    //    /**
//     * <p>查询角色权限</p >
//     * @param userName
//     * @author y
//     * @since 2021/10/11 16:18
//     * @return java.util.List<com.CST.entity.cb.BdSysUser>
//     */
//    @Override
//    public List<BdSysUser> getMenuByUserName(String userName) {
//        return baseMapper.getMenuByUserName(userName);
//    }
    @Autowired
    private BdSysRoleServiceImpl bdSysRoleService;
    @Resource
    private IZxAuthService zxAuthService;

    /**
     * <p>列表查询</p >
     *
     * @param sysUserDto
     * @return com.github.pagehelper.PageInfo<com.CST.entity.cb.BdSysUser>
     *
     * @author y
     * @since 2021/10/09 10:39
     */
    @Override
    public PageInfo<BdSysUser> getSysUserList(SysUserDTO sysUserDto) {
        PageHelper.startPage(sysUserDto.getPageNum(), sysUserDto.getPageSize());
        List<BdSysUser> sysUserList = baseMapper.getSysUserList(sysUserDto);
        Map<String, String> collect = bdSysRoleService.getSysRolesListAll()
                .stream()
                .collect(Collectors.toMap(BdSysRole::getId, BdSysRole::getRoleName));
        //  sysUserList.forEach(e-> e.setRoleId(collect.get(e.getRoleId())));
        sysUserList.forEach(e -> {
            String roleIdString = e.getRoleId();
            if (StringUtils.isNotBlank(roleIdString)) {// 获取角色ID字符串 "1,2"
                String[] roleIds = roleIdString.split(","); // 使用逗号拆分字符串为角色ID数组

                StringBuilder roleIdExpression = new StringBuilder(); // 用于构建最终的角色ID表达式
                for (String roleId : roleIds) {
                    roleIdExpression.append(collect.get(roleId)); // 构建表达式 collect.get(1) 或 collect.get(2)
                    roleIdExpression.append("+"); // 添加 + 符号，用于连接多个角色ID表达式
                }
                roleIdExpression.deleteCharAt(roleIdExpression.length() - 1); // 移除最后一个 + 符号

                e.setRoleId(roleIdExpression.toString());
            }

        });
        return new PageInfo<>(sysUserList);
    }

    @Override
    public List<BdSysUser> getSelectUser(List<String> userNameList) {
        return baseMapper.getSelectUser(userNameList);
    }

    @Override
    public int updateSysUser(BdSysUser bdSysUser) {
        return baseMapper.updateSysUser(bdSysUser);
    }


    @Override
    public BdSysUser getUserById(String leaderId) {
        return baseMapper.getUserById(leaderId);
    }

    @Override
    public List<ZxAuth> getAllUser(ApprovalUserBO approvalUserBO) {
        List<ZxAuth> list = zxAuthService.list();
        List<ZxAuth> allZxAuth = bdSysUserMapper.getAllZxAuth(approvalUserBO);
        List<String> idList = new ArrayList<>();
        if (!list.isEmpty()) {
            idList = list.stream().map(ZxAuth::getUserid).collect(Collectors.toList());
        }
        List<String> findIdList = idList;
        allZxAuth = allZxAuth.stream().filter(t -> !findIdList.contains(t.getUserid())).collect(Collectors.toList());
        return allZxAuth;
    }

    @Override
    public Object updatePassword() {
        LambdaQueryWrapper<BdSysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BdSysUser::getDelFlag,"0");
        lambdaQueryWrapper.ne(BdSysUser::getUserName,"admin");
        List<BdSysUser> bdSysUsers = bdSysUserMapper.selectList(lambdaQueryWrapper);
        //工号
        List<String> userIdList = bdSysUsers.stream().map(BdSysUser::getUserName).collect(Collectors.toList());
        LambdaQueryWrapper<ZxCardInformation> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(ZxCardInformation::getDeleteFlag,"0");
        List<ZxCardInformation> list = zxCardInformationMapper.selectList(lambdaQueryWrapper2);
        List<ZxCardInformation> filter = list.stream()
                .filter(t -> userIdList.contains(t.getUserId()))
                .collect(Collectors.toList());
        for (ZxCardInformation init: filter) {
            // 身份证后六位
            String idCard = "cbhs"+init.getIdCard();

            //对身份证后六位继续加密
            String crypt = MD5.crypt(idCard);
            //工号
            String userId = init.getUserId();
            bdSysUserMapper.updatePassword(userId,crypt);
        }
        return "OK";
    }

    public static List<BdSysMenu> treePower(List<BdSysMenu> list, BdSysMenu bdSysMenu) {
        List<BdSysMenu> children = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getParentId().equals(bdSysMenu.getId())) {
                treePower(list, list.get(i));
                children.add(list.get(i));
            }
        }
        bdSysMenu.setChildNodes(children);
        return children;
    }

}
